package io.iamting93.user.controller;

import io.iamting93.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author boting.guo
 * @date 2021/11/30 17:05
 */

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/register/{email}/{password}/{code}")
    public String register(HttpServletRequest request, HttpServletResponse response,
                        @PathVariable("email") String email,
                        @PathVariable("password") String password,
                        @PathVariable("code") String code) {
        String token = userService.register(email, password, code);
        if (token != null) {
            Cookie cookie = new Cookie(token, email);
            cookie.setMaxAge(20);
            cookie.setPath("/");
            response.addCookie(cookie);
            return "0";
        }
        return "1";
    }

    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email) {
        return userService.isRegistered(email);
    }

    @GetMapping("/login/{email}/{password}")
    public String login(HttpServletRequest request, HttpServletResponse response,
                        @PathVariable("email") String email,
                        @PathVariable("password") String password) {

        String token = userService.login(email, password);
        if (token != null) {
            Cookie cookie = new Cookie("token", token);
            cookie.setMaxAge(20);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return token != null ? "true" : "false";
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable("token") String token) {
        return userService.info(token);
    }
}
